﻿using System.Collections.Generic;
using System.Security.Principal;
using System.Web.Security;

namespace SubSonic.Security
{
    public class SubSonicPrincipal : IPrincipal
    {
        private SubSonic.Security.SubSonicIdentity _Identity;
        private List<string> _Roles = new List<string>();

        public SubSonicPrincipal(IIdentity identity){
            _Identity = (SubSonic.Security.SubSonicIdentity)identity;
        }

        public SubSonicPrincipal(IIdentity identity, List<string> roles){
            _Identity = (SubSonic.Security.SubSonicIdentity)identity;
            _Roles = roles;
        }

        public IIdentity Identity{
            get { return _Identity; }
        }

        public bool IsInRole(string role){
            role = role.ToLower();
            bool ret = false;

            if (_Roles.Contains(role))
                ret = true;

            return ret;
        }

        public static IPrincipal ValidateUser(string username, string password, MembershipPasswordFormat passwordFormat){
            SubSonic.Security.SubSonicPrincipal p = null;

            //Authenticate user, get IIdentity
            IIdentity identity = Helper.GetIdentity(username, password, passwordFormat);
            if (identity.IsAuthenticated)
            {
                p = new SubSonic.Security.SubSonicPrincipal(identity);

                if (Roles.Enabled)
                {
                    string[] userRoles = Roles.GetRolesForUser(username);
                    p._Roles = new List<string>(userRoles);
                }
            }
            return p;
        }

        public static SubSonicPrincipal UnauthenticatedUser(){
            return new SubSonic.Security.SubSonicPrincipal(Helper.GetIdentity());
        }

    }
}